package com.feign.producer.service.impl;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.feign.api.consumer.RemoteConsumerService;
import com.feign.core.domain.AjaxResult;
import com.feign.producer.mapper.ProducerMapper;
import com.feign.producer.model.ProducerInfo;
import com.feign.producer.service.IProducerService;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ProducerServiceImpl implements IProducerService {

    @Resource
    private RemoteConsumerService remoteConsumerService;

    @Resource
    private ProducerMapper producerMapper;

    @Override
    public String getProducerMessage() {
        AjaxResult result = remoteConsumerService.getConsumeMessage();
        if(result.isSuccess()){
            return String.valueOf(result.get("data"));
        }
        return String.valueOf(result.get("msg"));
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public String consumeMessagePost() {
        ProducerInfo producerInfo = new ProducerInfo();
        producerInfo.setName("producer2");
        producerMapper.insert(producerInfo);

        //远程调用失败时抛出异常,全局事务回滚
        AjaxResult result = remoteConsumerService.consumeMessagePost();
        if(result.isSuccess()){
          return String.valueOf(result.get("data"));
        }else{
            throw new RuntimeException(String.valueOf(result.get("msg")));
        }
    }

    @Override
    public AjaxResult getProducerAll() {
        return AjaxResult.success(producerMapper.selectList(null));
    }

    @Override
    public AjaxResult deleteProducer(ProducerInfo producerInfo) {
        return AjaxResult.success(producerMapper.deleteById(producerInfo));
    }

    @Override
    public AjaxResult updateProducer(ProducerInfo producerInfo) {
        UpdateWrapper<ProducerInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",producerInfo.getId());
        return AjaxResult.success(producerMapper.update(producerInfo, updateWrapper));
    }
}
